package com.gm.corejava.book2;

import javax.swing.*;
import javax.swing.Timer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: camark@sina.cn
 * Date: 13-12-27
 * Time: 上午10:43
 */
public class TrayTest {

    public static void main(String[] args) throws AWTException {
        final TrayIcon trayIcon;

        if(!SystemTray.isSupported()){
            System.err.println("System Tray is not support!");
            return;
        }

        SystemTray systemTray=SystemTray.getSystemTray();
        Image image=Toolkit.getDefaultToolkit().getImage("cookie.png");

        PopupMenu popupMenu=new PopupMenu();
        MenuItem exitMenu=new MenuItem("Exit");
        exitMenu.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        popupMenu.add(exitMenu);

        trayIcon=new TrayIcon(image,"Futune",popupMenu);
        trayIcon.setImageAutoSize(true);
        trayIcon.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                trayIcon.displayMessage("Do you want to Exit?",
                        "Right click on the cion and select exit!",
                        TrayIcon.MessageType.INFO);
            }
        });

        systemTray.add(trayIcon);

        final java.util.List<String> futunes=readFutunes();

        Timer timer=new Timer(10000,new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int index=(int)(futunes.size()*Math.random());
                trayIcon.displayMessage("Your Futune",futunes.get(index),TrayIcon.MessageType.INFO);
            }
        });
        timer.start();
    }

    private static List<String> readFutunes() {
        java.util.List<String> futunes=new ArrayList<String>();

        try{
            Scanner scanner=new Scanner(new File("fortunes"));
            StringBuilder futune=new StringBuilder();

            while(scanner.hasNextLine())
            {
                String line=scanner.nextLine();
                if(line.equals("%")){
                    futunes.add(futune.toString());
                    futune=new StringBuilder();
                }
                else{
                    futune.append(line);
                    futune.append(" ");
                }
            }
        }catch (IOException e)
        {
            e.printStackTrace();
        }

        return futunes;
    }
}
